package org.xserver.component.redis.spring;

import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.beans.factory.FactoryBean;
import org.springframework.beans.factory.InitializingBean;

import redis.clients.jedis.Jedis;
import redis.clients.jedis.JedisPool;
import redis.clients.jedis.JedisPoolConfig;

public class RedisPoolFactory implements FactoryBean<JedisPool>,
		InitializingBean {
	private static final Logger log = LoggerFactory
			.getLogger(RedisPoolFactory.class);
	private String host;
	private JedisPool jedisPool;
	private JedisPoolConfig jedisPoolConfig;
	private int port;

	public RedisPoolFactory(JedisPoolConfig jedisPoolConfig, String host,int port) {
		this.host = host;
		this.jedisPoolConfig = jedisPoolConfig;
		this.jedisPool = new JedisPool(jedisPoolConfig, host, port);
		log.info("create redis connection to {}, config as {}", host,
				"ReflectionUtil.getTargetInfo(jedisPoolConfig)");
	}

	public String getHost() {
		return host;
	}

	public void setHost(String host) {
		this.host = host;
	}

	public JedisPool getJedisPool() {
		return jedisPool;
	}

	public void setJedisPool(JedisPool jedisPool) {
		this.jedisPool = jedisPool;
	}

	public JedisPoolConfig getJedisPoolConfig() {
		return jedisPoolConfig;
	}

	public void setJedisPoolConfig(JedisPoolConfig jedisPoolConfig) {
		this.jedisPoolConfig = jedisPoolConfig;
	}

	@Override
	public JedisPool getObject() throws Exception {
		return jedisPool;
	}

	@Override
	public Class<JedisPool> getObjectType() {
		return JedisPool.class;
	}

	@Override
	public boolean isSingleton() {
		return true;
	}

	public void release(Jedis resource) throws Exception {
		resource.close();
	}

	@Override
	public void afterPropertiesSet() throws Exception {
		// TODO initialize
	}

	public int getPort() {
		return port;
	}

	public void setPort(int port) {
		this.port = port;
	}
	
}
